from datetime import timedelta
from typing import Annotated, Any

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.security import OAuth2PasswordRequestForm

from app.service import crud
from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser
from app.core import security
from app.core.config import settings
from app.core.security import get_password_hash
from app.model.models import Message, NewPassword, Token, UserPublic
from app.core.utils import (
    generate_password_reset_token,
    generate_reset_password_email,
    send_email,
    verify_password_reset_token,
)
router = APIRouter(tags=["login"])

@router.post("/login/access-token")
def login_access_token(
    session: SessionDep, form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
) -> Token:
    """
    用户登录并获取访问令牌。

    Args:
        session (SessionDep): 数据库会话依赖项。
        form_data (OAuth2PasswordRequestForm): 包含用户名（邮箱）和密码的表单数据。

    Returns:
        Token: 包含访问令牌的对象。

    Raises:
        HTTPException: 如果用户不存在、密码错误或用户未激活，抛出相应的HTTP异常。
    """
    user = crud.authenticate(
        session=session, email=form_data.username, password=form_data.password
    )
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect email or password")
    elif not user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    return Token(
        access_token=security.create_access_token(
            user.id, expires_delta=access_token_expires
        )
    )


@router.post("/login/test-token", response_model=UserPublic)
def test_token(current_user: CurrentUser) -> Any:
    """
    测试当前用户的访问令牌是否有效。

    Args:
        current_user (CurrentUser): 当前已验证的用户对象。

    Returns:
        Any: 返回当前用户对象，表示令牌有效。
    """
    return current_user


@router.post("/password-recovery/{email}")
def recover_password(email: str, session: SessionDep) -> Message:
    """
    通过电子邮件发送密码重置链接。

    Args:
        email (str): 用户的电子邮件地址。
        session (SessionDep): 数据库会话依赖项。

    Returns:
        Message: 返回操作结果消息，指示密码重置邮件是否成功发送。

    Raises:
        HTTPException: 如果用户不存在，返回404错误。
    """

    user = crud.get_user_by_email(session=session, email=email)

    if not user:
        raise HTTPException(
            status_code=404,
            detail="The user with this email does not exist in the system.",
        )
    password_reset_token = generate_password_reset_token(email=email)
    email_data = generate_reset_password_email(
        email_to=user.email, email=email, token=password_reset_token
    )
    send_email(
        email_to=user.email,
        subject=email_data.subject,
        html_content=email_data.html_content,
    )
    return Message(message="Password recovery email sent")


@router.post("/reset-password/")
def reset_password(session: SessionDep, body: NewPassword) -> Message:
    """
    重置用户密码。
    
    该接口用于通过验证密码重置令牌后，更新用户的密码。
    
    Args:
        session (SessionDep): 数据库会话依赖项。
        body (NewPassword): 包含新密码和重置令牌的请求体。
    
    Returns:
        Message: 返回操作结果消息，指示密码是否成功更新。
    
    Raises:
        HTTPException: 如果令牌无效、用户不存在或用户未激活，抛出相应的HTTP异常。
    """
    email = verify_password_reset_token(token=body.token)
    if not email:
        raise HTTPException(status_code=400, detail="Invalid token")
    user = crud.get_user_by_email(session=session, email=email)
    if not user:
        raise HTTPException(
            status_code=404,
            detail="The user with this email does not exist in the system.",
        )
    elif not user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    hashed_password = get_password_hash(password=body.new_password)
    user.hashed_password = hashed_password
    session.add(user)
    session.commit()
    return Message(message="Password updated successfully")


@router.post(
    "/password-recovery-html-content/{email}",
    dependencies=[Depends(get_current_active_superuser)],
    response_class=HTMLResponse,
)
def recover_password_html_content(email: str, session: SessionDep) -> Any:
    """
    通过电子邮件发送密码重置的HTML内容。
    
    Args:
        email (str): 用户的电子邮件地址。
        session (SessionDep): 数据库会话依赖项。
    
    Returns:
        HTMLResponse: 包含密码重置链接的HTML内容。
    
    Raises:
        HTTPException: 如果用户不存在，返回404错误。
    
    Notes:
        - 该接口仅限超级用户访问。
        - 生成的HTML内容包含密码重置令牌和主题信息。
    """
    user = crud.get_user_by_email(session=session, email=email)

    if not user:
        raise HTTPException(
            status_code=404,
            detail="The user with this username does not exist in the system.",
        )
    password_reset_token = generate_password_reset_token(email=email)
    email_data = generate_reset_password_email(
        email_to=user.email, email=email, token=password_reset_token
    )

    return HTMLResponse(
        content=email_data.html_content, headers={"subject:": email_data.subject}
    )
